package com.zzy.prototype;

import java.io.Serializable;

/**
 * 通过实现Cloneable接口完成原型模式
 * 只实现接口是浅克隆，对象中包含的引用类型是传递的，不是新的
 * 注：这里实现Serializable是给深拷贝用的，那边演示引用类型的深拷贝，用到的引用类型就是这里的Sheep
 */
public class Sheep implements Cloneable, Serializable {
    private String name;
    private int age;
    private String color;

    private Sheep Friend;

    public Sheep(String name, int age, String color) {
        this.name = name;
        this.age = age;
        this.color = color;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public Sheep getFriend() {
        return Friend;
    }

    public void setFriend(Sheep friend) {
        Friend = friend;
    }

    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", color='" + color + '\'' +
                '}';
    }

    @Override
    public Object clone() {
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }
}

class Client {
    public static void main(String[] args) {
//        sheep1>>>Sheep{name='zzy', age=18, color='black'},sheep1.hashCode>>>1784662007
//        sheep2>>>Sheep{name='zzy', age=18, color='black'},sheep2.hashCode>>>1394336709
//        sheep1.friend>>>Sheep{name='mike', age=28, color='black'},sheep1.friend.hashCode>>>1387228415
//        sheep3.friend>>>Sheep{name='mike', age=28, color='black'},sheep3.friend.hashCode>>>1387228415

        Sheep sheep1 = new Sheep("zzy", 18, "black");
        Sheep sheep2 = (Sheep) sheep1.clone();

        System.out.println("sheep1>>>" + sheep1 + ",sheep1.hashCode>>>" + sheep1.hashCode());
        System.out.println("sheep2>>>" + sheep2 + ",sheep2.hashCode>>>" + sheep2.hashCode());

        Sheep friend = new Sheep("mike", 28, "black");
        sheep1.setFriend(friend);
        Sheep sheep3 = (Sheep) sheep1.clone();
        System.out.println("sheep1.friend>>>" + sheep1.getFriend() + ",sheep1.friend.hashCode>>>" + sheep1.getFriend().hashCode());
        System.out.println("sheep3.friend>>>" + sheep3.getFriend() + ",sheep3.friend.hashCode>>>" + sheep3.getFriend().hashCode());
    }
}